package com.ruoyi.common.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.entity.Category;
import com.ruoyi.common.mapper.CategoryMapper;
import com.ruoyi.common.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    private final CategoryMapper categoryMapper;

    @Autowired
    public CategoryServiceImpl(CategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
    }

    @Override
    public List<Category> getAllActiveCategories() {
        return categoryMapper.selectAllActive();
    }

    @Override
    public Category getCategoryById(Integer id) {
        return categoryMapper.selectById(id);
    }

    @Override
    public Category saveCategory(Category category) {
        category.setCreatedAt(LocalDateTime.now());
        category.setUpdatedAt(LocalDateTime.now());
        category.setIsActive(category.getIsActive() != null ? category.getIsActive() : 1); // 默认启用
        categoryMapper.insert(category);
        return category; // id 已被 MyBatis 设置
    }

    @Override
    public Category updateCategory(Integer id, Category category) {
        Category existingCategory = getCategoryById(id);
        if (existingCategory == null) {
            return null; // 或抛出异常
        }
        // 更新字段
        existingCategory.setTitle(category.getTitle());
        existingCategory.setIcon(category.getIcon());
        existingCategory.setSortOrder(category.getSortOrder());
        existingCategory.setIsActive(category.getIsActive());
        existingCategory.setUpdatedAt(LocalDateTime.now());

        categoryMapper.update(existingCategory);
        return existingCategory;
    }

    @Override
    public void deleteCategory(Integer id) {
        categoryMapper.deleteById(id);
    }

    @Override
    public Category selectExist(String categoryName) {
        Category category = categoryMapper.selectOne(Wrappers.<Category>lambdaQuery()
                .eq(Category::getTitle, categoryName));


        return category;
    }

    @Override
    public Category saveSpiderCategory(Category category) {
        int insert = categoryMapper.insert(category);
        if (insert > 0) {
            return category;
        }
        return null;
    }
}